use std::fs::{self, File, OpenOptions};
use std::io::{self, BufReader, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use super::models::FileData;
use base64::Engine;
pub fn add_file(_path: &str, file_type: Option<&str>) {

    let open_file = fs::File::open(_path);
    if let Err(_) = open_file {
        let mut _file = fs::File::create(_path).unwrap();
        if file_type == Some("user") {
            _file.write_all(b"[{\"imgtype\": \".jpeg\",\"mes_type\": \"image\",\"user_name\": \"default_avatar\",\"name\": \"default_avatar\",\"url\": \"\",\"user_id\": \"user_01\",\"is_current\": \"true\" }]").unwrap();
        } else {
            _file.write_all(b"[]").unwrap();
        }
    }
}

pub fn add_dir(_path: &str, file_type: Option<&str>) {
    let open_file = fs::create_dir(_path);
    if let Err(_) = open_file {
        println!("文件夹已存在");
    }

    if file_type == Some("user") {
        let default_images_path = "./src/fs_file/default_image/default_avatar.jpg";
        let image_path = Path::new(default_images_path);

        let filename = image_path.file_stem()
            .and_then(|n| n.to_str())
            .unwrap_or_default()
            .to_string();

        let ext = image_path.extension()
            .and_then(|e| e.to_str())
            .unwrap_or("unknown")
            .to_lowercase();

        let image_data = if let Ok(file_data) = fs::read(&image_path) {
            super::models::ImageData {
                name: filename.to_string(),
                imgtype: ext.to_string(),
                base64_header:"data:image/jpeg;base64,".to_string(),
                url: base64::engine::general_purpose::STANDARD.encode(&file_data),
                mes_type: "image".to_string(),
                user_id: Some("default_user".to_string()),
            }
        } else {
            panic!("默认头像不存在")
        };
        
        let image_json = serde_json::to_string(&image_data).expect("序列化失败");
        let entry: serde_json::Value = serde_json::from_str(&image_json).unwrap();
        super::image_ops::add_image(_path, &entry);
    }
}

pub fn copy_file(origin_path: &Path) -> Result<FileData, String> {
    let temp_path = origin_path.with_extension("tmp");
    let mut temp_file = OpenOptions::new()
        .write(true)
        .create(true)
        .open(&temp_path)
        .map_err(|e| format!("文件打开失败: {}", e))?;

    let mut origin_file = fs::File::open(origin_path)
        .map_err(|e| format!("文件打开失败: {}", e))?;
    
    let mut origin_buffer = BufReader::new(&mut origin_file);
    io::copy(&mut origin_buffer, &mut temp_file)
        .map_err(|e| format!("复制文件失败: {}", e))?;

    Ok(FileData {
        file: temp_file,
        path: temp_path,
        name: None,
    })
}

pub fn replace_file(temp_path: &Path, origin_path: &Path) -> Result<String, String> {
    std::fs::rename(temp_path, origin_path)
        .map_err(|e| format!("文件替换失败: {}", e))?;
    Ok("成功替换".to_string())
}